﻿using System.Dynamic;
using Behavioral.Private;

namespace Behavioral
{
    public class DynamicContext : DynamicObject, IDynamicContextSetter, IDynamicContextGetter, IContextGetter
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            bool isEligibleAsSetter = (args.Length == 1);
            if (isEligibleAsSetter)   
            {
                this.SetContext(binder.Name, args[0]);
                result = null;
                return isEligibleAsSetter;
            }
            return base.TryInvokeMember(binder, args, out result);
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            this.SetContext(binder.Name, value);
            return true;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = this.GetContext(binder.Name);
            return true;
        }
    }
}
